<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '../plugins/axios'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 搜索参数
const searchParams = ref({
  keyword: '',
  page: 1,
  rows: 5,
  sortWay: 'DESC',
  sortColumn: 'id'
})

// 分页信息
const pagination = ref({
  total: 0
})

// 新增站点数据相关变量
const siteList = ref([])
const selectedSites = ref([])

// 用户表单
const userForm = ref({
  id: '',
  displayId: '',
  username: '',
  pwd: 'Hello@123456',
  realname: '',
  phone: '',
  sex: '',
  email: '',
  birthday: '',
  hireDate: '',
  duty: '',
  isAdmin: 0,
  role: 0,
  siteIds: []
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 性别选项
const sexOptions = [
  { value: '男', label: '男' },
  { value: '女', label: '女' }
]

// 角色选项
const roleOptions = [
  { value: 0, label: '研发工程师' },
  { value: 1, label: '现场工程师' },
  { value: 3, label: '其他' }
]

// 添加手机号验证相关状态
const phoneValidating = ref(false)
const phoneExists = ref(false)

// 表单规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realname: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value || phoneValidating.value) {
          callback()
          return
        }
        
        validatePhoneExists(value).then(valid => {
          if (valid) {
            callback()
          } else {
            if (phoneExists.value) {
              callback(new Error('该手机号码已被注册'))
            } else {
              callback(new Error('手机号码格式不正确'))
            }
          }
        })
      }, 
      trigger: 'blur' 
    }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色类型', trigger: 'change' }
  ]
}

const userFormRef = ref(null)


// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const response = await axios.post('/user/queryByCondition', {
      ...searchParams.value
    })
    debugger
    if (response.data.code === 1) {
      tableData.value = response.data.data.data || []
      pagination.value.total = response.data.data.total
    } else {
      ElMessage.error(response.data.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  searchParams.value.page = 1
  fetchUserList()
}

// 处理重置
const handleReset = () => {
  searchParams.value = {
    keyword: '',
    page: 1,
    rows: 5,
    sortWay: 'DESC',
    sortColumn: 'id'
  }
  fetchUserList()
}

// 处理新增
const handleAdd = () => {
  dialogTitle.value = '新增员工'
  userForm.value = {
    id: '',
    displayId: '',
    username: '',
    pwd: 'Hello@123456',
    realname: '',
    phone: '',
    sex: '',
    email: '',
    birthday: '',
    hireDate: new Date().toISOString().split('T')[0],
    duty: '',
    isAdmin: 0,
    role: 0,
    siteIds: []
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = async (row) => {
  dialogTitle.value = '编辑员工'
  userForm.value = { 
    ...row, 
    displayId: row.displayId || '',
    siteIds: [] 
  }
  
  // 如果有用户ID，则获取该用户的站点列表
  if (row.id) {
    try {
      const response = await axios.get(`/site/findSiteByUserId/${row.id}`)
      if (response.data.code === 1) {
        userForm.value.siteIds = (response.data.data || []).map(site => site.id)
      }
    } catch (error) {
      console.error('获取用户站点失败:', error)
    }
  }
  
  dialogVisible.value = true
}

// 验证手机号是否已存在
const validatePhoneExists = async (phone) => {
  // 如果是编辑模式且手机号没变，不需要验证
  if (userForm.value.id && phone === tableData.value.find(user => user.id === userForm.value.id)?.phone) {
    return true
  }
  
  // 先验证手机号格式是否正确
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phone)) {
    return false
  }
  
  phoneValidating.value = true
  
  try {
    const response = await axios.post("user/queryByPhone", { phone })
    
    if (response.data.code === 1) {
      const exists = !!response.data.data // 如果有数据返回，说明手机号已存在
      phoneExists.value = exists
      
      if (exists) {
        ElMessage.warning('该手机号码已被注册')
        return false
      }
    }
    return true
  } catch (error) {
    console.error('验证手机号失败:', error)
    return false
  } finally {
    phoneValidating.value = false
  }
}

// 处理手机号输入完成后的验证
const handlePhoneBlur = () => {
  if (userForm.value.phone) {
    validatePhoneExists(userForm.value.phone)
  }
}

// 处理保存
const handleSave = async () => {
  if (!userFormRef.value) return
  
  // 如果是新增且手机号存在，不允许保存
  if (!userForm.value.id && phoneExists.value) {
    ElMessage.error('该手机号码已被注册，请更换后再试')
    return
  }
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 创建包含站点数据的提交表单
        const submitData = {
          ...userForm.value,
          // 确保其他必要字段也包含在内
        }
        
        const url = userForm.value.id ? '/user/update' : '/user/regist'
        const response = await axios.post(url, submitData)
        
        if (response.data.code === 1) {
          // 如果需要，保存用户站点关联
          ElMessage.success(userForm.value.id ? '修改成功' : '添加成功')
          dialogVisible.value = false
          fetchUserList()
        } else {
          ElMessage.error(response.data.msg || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 保存用户站点关联
const saveUserSites = async (userId, siteIds) => {
  try {
    const response = await axios.post('/user/sites/save', {
      userId,
      siteIds
    })
    
    if (response.data.code !== 1) {
      ElMessage.warning('用户站点保存失败')
    }
  } catch (error) {
    console.error('保存用户站点失败:', error)
    ElMessage.warning('用户站点保存失败')
  }
}

// 处理排序
const handleSortChange = ({ prop, order }) => {
  searchParams.value.sortColumn = prop
  searchParams.value.sortWay = order === 'ascending' ? 'ASC' : 'DESC'
  fetchUserList()
}

// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  // 处理带时区的ISO格式日期
  if (dateString.includes('T')) {
    return dateString.split('T')[0]
  }
  // 处理普通的日期时间格式
  return dateString.split(' ')[0]
}

// 添加重置密码的方法
const handleResetPassword = (row) => {
  ElMessageBox.confirm(
    '确定要将该用户的密码重置为 Hello@123456 吗？',
    '重置密码',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await axios.put('/user/pwd/update', {
        id: row.id,
        pwd: 'Hello@123456'
      })
      
      if (response.data.code === 1) {
        ElMessage.success('密码重置成功')
      } else {
        ElMessage.error(response.data.msg || '密码重置失败')
      }
    } catch (error) {
      console.error('密码重置失败:', error)
      ElMessage.error('密码重置失败')
    }
  }).catch(() => {
    // 取消重置密码操作
  })
}

// 获取所有站点数据
const fetchSiteList = async () => {
  try {
    const response = await axios.get('/site/queryAll')
    if (response.data.code === 1) {
      siteList.value = response.data.data || []
    } else {
      ElMessage.error(response.data.msg || '获取站点列表失败')
    }
  } catch (error) {
    console.error('获取站点列表失败:', error)
    ElMessage.error('获取站点列表失败')
  }
}

onMounted(() => {
  fetchUserList()
  fetchSiteList() // 在组件挂载时获取站点数据
})

// 根据角色值获取角色名称
const getRoleName = (role) => {
  const option = roleOptions.find(item => item.value === Number(role))
  return option ? option.label : '未知角色'
}

// 根据角色值获取标签类型
const getRoleTagType = (role) => {
  const roleTypeMap = {
    0: '',         // 研发工程师 - 默认灰色
    1: 'success',  // 现场工程师 - 绿色
    3: 'warning'   // 其他 - 橙色
  }
  return roleTypeMap[role] || 'info'
}

// 处理分页
const handleSizeChange = (val) => {
  searchParams.value.rows = val
  searchParams.value.page = 1
  fetchUserList()
}

const handleCurrentChange = (val) => {
  searchParams.value.page = val
  fetchUserList()
}
</script>

<template>
  <div class="user-manager">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="searchParams">
        <el-form-item label="关键字">
          <el-input 
            v-model="searchParams.keyword" 
            placeholder="用户名/姓名/手机号" 
            clearable 
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增员工</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      @sort-change="handleSortChange"
    >
      <el-table-column prop="username" label="用户名" sortable="custom" />
      <el-table-column prop="realname" label="姓名" sortable="custom" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="sex" label="性别" width="80" />
      <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
      <el-table-column prop="duty" label="职责" show-overflow-tooltip />
      <!-- 添加 role 列 -->
      <el-table-column label="角色" show-overflow-tooltip>
        <template #default="scope">
          <el-tag
            :type="getRoleTagType(scope.row.role)"
            effect="light"
          >
            {{ getRoleName(scope.row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="hireDate" label="入职日期" sortable="custom">
        <template #default="{ row }">
          {{ formatDate(row.hireDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" link @click="handleResetPassword(row)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="searchParams.page"
        v-model:page-size="searchParams.rows"
        :page-sizes="[5, 10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="userFormRef?.resetFields()"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="!!userForm.id" />
        </el-form-item>
        <el-form-item label="密码" prop="pwd" v-if="!userForm.id">
          <el-input v-model="userForm.pwd" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="userForm.realname" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input 
            v-model="userForm.phone" 
            placeholder="请输入手机号码" 
            @blur="handlePhoneBlur"
            :loading="phoneValidating"
          />
          <span v-if="phoneExists" class="error-tip">该手机号码已被注册</span>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="userForm.sex" placeholder="请选择性别">
            <el-option
              v-for="option in sexOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="userForm.birthday"
            type="date"
            placeholder="选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="入职日期">
          <el-date-picker
            v-model="userForm.hireDate"
            type="date"
            placeholder="选择入职日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="职责">
          <el-input v-model="userForm.duty" />
        </el-form-item>
        <el-form-item label="角色类型" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option
              v-for="option in roleOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员">
          <el-switch
            v-model="userForm.isAdmin"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="关联站点">
          <div class="site-checkbox-group">
            <el-checkbox
              v-model="userForm.siteIds"
              v-for="site in siteList"
              :key="site.id"
              :value="site.id"
            >
              {{ site.siteName }}
            </el-checkbox>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-manager {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-pagination) {
  padding: 20px 0;
  background-color: #fff;
  border-radius: 4px;
}

:deep(.el-table) {
  margin-top: 20px;
}

/* 添加站点复选框样式 */
.site-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.site-checkbox-group .el-checkbox {
  margin-right: 15px;
  margin-bottom: 10px;
}

/* 添加手机号错误提示样式 */
.error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-left: 5px;
}
</style>